/**
 * 
 */

//ipPort = '10.58.88.212:8080';
Ext.define('Server.Server', {
	extend: 'Ext.grid.Panel',
	alias: 'server.server',
    
    initComponent: function() {
		me_server = this;
	
    	var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
            clicksToEdit: 1
        });	
    	Ext.apply(this, {
			//id: '__server_tab__',
			title: 'Servers',
			id: 'serverList',
			closable: false,
			height: '100%',
			width: '100%',
			store: this.store(),
    		columns:[{
    			text:'ID',
    			dataIndex:'id',
				flex: 1
    		},
//    		    Ext.create('Ext.grid.RowNumberer'),
    		{
    			text:'Name',
    			dataIndex:'name',
    			flex: 2
//    			editor: {
//					allowBlank: false
//                }
    		},{
    			text:'Server',
    			dataIndex:'hostServer',
    			flex: 2
//				width: 150
//    			editor: {
//                    allowBlank: false
//                }
    		},{
    			text:'URL',
    			dataIndex:'hostUrl',
    			flex: 4
//				width: 150
//    			editor: {
//                    allowBlank: false
//                }
    		},{
    			text:'Daily Run',
    			dataIndex:'isDailyRun',
				xtype: 'booleancolumn',
				flex: 2,
				trueText: 'Yes',
				falseText: 'No' 
//    			editor: {
//					xtype: 'checkboxfield',
//                    allowBlank: false
//                }
    		},{
    			text:'Daily Run Time',
    			dataIndex:'runSchedule',
    			flex: 4
//    			width: 150
//    			editor: {
//					xtype: 'timefield',
//					disabled: true
//                }
    		},{
    			text:'User Name',
    			dataIndex:'user',
    			flex: 2
//    			editor: {
//                    //allowBlank: false
//                }
//    		},{
//    			text:'Password',
//    			dataIndex:'password',
//    			flex: 2
////    			editor: {
////                    //allowBlank: false
////                }
    		}],
    		plugins: [cellEditing],
			dockedItems: [{
                xtype: 'toolbar',
                dock: 'top',
                items: [{
                    text: 'New',
                    handler: function() {
                    	
                    	win = new serverWindow();
                        win.show()

					}
                },{
                    text: 'Delete',
                    handler: function() {
                    	Ext.MessageBox.confirm('Delete', 'Do you really want to delete the Server? It will be removed from all profiles!', function(id){
                    		if (id != 'yes'){
                    			return;
                    		} else {
                            	me_server.setLoading('Deleting');
        						var m = me_server.getSelectionModel();
        						var r = m.getLastSelected();
        						if (r) {
        						Ext.Ajax.request({
        							url: 'http://' + ipPort + '/bpcsaveserver/' + r.data.id,
        							method: 'DELETE',
        							callback: function(){
        								me_server_server.profileTab.onServersModified();
        								me_server.store.remove(r);
        								caseList.serverStore.load();
        	//							me_server.store.load();
        		//						me_server.setLoading(false);
        								Ext.Ajax.request({
        									url: 'http://' + ipPort + '/bpcmetadata',
        									method: 'GET',
        									success: function(response){
        										var metaData = Ext.decode(response.responseText);
        										var profiles = new Array;
        										if (metaData.profiles != null) {
	    											if (!(metaData.profiles.length)) {
	    												profiles[0] = metaData.profiles;
	    											} else {
	    												profiles = metaData.profiles;
	    											};
        										};
        						/*				if (profiles.length == 0) {
        											me_profile.listGrid.store.load();
													me_server.store.load();
													caseList.serverStore.load();
													me_server.setLoading(false);
        										}*/
        										if (profiles.length == 0) {
        										//	caseList.serverStore.load();
        										//	me_server.setLoading(false);
        										}
        										
        									/*	var deletedProfiles = 0;
        										var toBeDeletedProfiles = 0;
												for (i = 0; i < profiles.length; i++){
													if (metaData.profiles[i].serverId == r.data.id){
														++toBeDeletedProfiles;
													}
												}*/
												for (i = 0; i < profiles.length; ++i) {
													if (metaData.profiles[i].serverId == r.data.id){
														Ext.Ajax.request({
															method: 'DELETE',
															url: 'http://' + ipPort + '/bpcsaveprofile/' + profiles[i].id,
															callback: function(){
																me_profile.listGrid.store.load();
																//me_profile.listGrid.store.load();
																me_server.store.load();
																me_server.setLoading(false);
																//caseList.serverStore.load();
															/*	++deletedProfiles;
																if (toBeDeletedProfiles == deletedProfiles)
																	me_server.setLoading(false);*/
															}
														});
													};
												};
        									}
        								});
        								me_server.doLayout();
        							}
        						})		
        						}
        						else {
        							alert('Please select a line!');
        						}
                    		};
                    	})

					}
                }, {
                    text: 'Edit',
                    handler: function() {
                    	var m = me_server.getSelectionModel();
						var r = m.getLastSelected();
						if (!(r)) {
							alert('Please select a line!');
							return;
						};
                    	win = new serverWindow({action:'edit', sId:r.data.id});

                    	var nameField = win.items.items[0].items.items[0];
            			var hostServerField = win.items.items[0].items.items[1];
            			var hostUrlField = win.items.items[0].items.items[2];
            			var isDailyRunField = win.items.items[1].items.items[0].items.items[0].items.items[0];
            			var runScheduleField = win.items.items[1].items.items[0].items.items[1];
            			var userField = win.items.items[1].items.items[1];
            			var passwordField = win.items.items[1].items.items[2];
            			
            			            			
            			nameField.setValue(r.data.name);
            			hostServerField.setValue(r.data.hostServer);
            			hostUrlField.setValue(r.data.hostUrl);
            			isDailyRunField.setValue(r.data.isDailyRun);
            			runScheduleField.setRawValue(r.data.runSchedule);
            			userField.setValue(r.data.user);
            			passwordField.setValue(r.data.password);
                    	
                    	win.show(); 	
                    	

                    	
//                    	
//						/*var data = [];
//						var tmpStore = Ext.create('Ext.data.Store', {
//							model: 'Server'
//						});
//						*/
//						me_server.store.each(function(server){
//							server.phantom = false;
//							server.dirty = true;							
//							//data.push(server);
//							//tmpStore.add(server);
//						});
//						//tmpStore.loadData(data);
//						me_server.store.update({
//							callback: function(records, operation, success){
//								if (success) {
//									me_server.store.loadData(records);
//									me_server.fireEvent('serversmodified', records);
//								}
//							}
//						});
//						//tmpStore.save();
					}
                }]
            }]		
		});
    	me_server.callParent(arguments);
		me_server.addEvents('serversmodified');
	},
	

	
		
	store: function(){
		this.store = Ext.create('Ext.data.Store', {
			model: 'Server'
//				'Server'/*,
//			data: [] 
//			       {name:'n1', value:'v1'},
//			       {name:'n2', value:'v2'}
//			]*/
		});
		this.store.load();
		return this.store;
	}
});



Ext.define('serverWindow',{
	extend: 'Ext.window.Window', 
	title: 'Server',
    closable: true,
    closeAction: 'hide',
    width: 600,
    height: 230,
    modal: true,
    layout: 'border',
//    bodyStyle: 'padding: 5px;',
    items: [{
        region: 'west',
    	width: 300,
        border: 0,
//        height: '100%',
        items:[{
        	xtype: 'textfield',
        	padding: 3,
        	width: 250,
        	fieldLabel: 'Name',
        	labelAlign: 'top',
        	id: 'name'
        },{
        	xtype: 'textfield',
        	padding: 3,
        	width: 250,
        	fieldLabel: 'Server',
        	labelAlign: 'top',
        	id: 'hostServer'
        },{
        	xtype: 'textfield',
        	padding: 3,
        	width: 250,
        	fieldLabel: 'Url',
        	labelAlign: 'top',
        	id: 'hostUrl'
        },{
        	xtype: 'container',
        	padding: 3,
        	layout: 'hbox',
        	items:[{
        		xtype: 'button',
            	padding: 3,
        		text: 'OK',
        		handler: function(){
        			if (win.action != 'edit'){
        				me_server.setLoading('Creating new server...');
        			} else {
        				me_server.setLoading('Saving server...');
        			};
        			var name = win.items.items[0].items.items[0].value;
        			var hostServer = win.items.items[0].items.items[1].value;
        			var hostUrl = win.items.items[0].items.items[2].value;
        			var isDailyRun = win.items.items[1].items.items[0].items.items[0].items.items[0].value;
        			var runSchedule = win.items.items[1].items.items[0].items.items[1].value;
        			if (!(isDailyRun)) runSchedule = '';
        			var user = win.items.items[1].items.items[1].value;
        			var password = win.items.items[1].items.items[2].value;
        			
        			if (win.action == 'edit'){
        				var serverId = win.sId;
        			} else {
        				var serverId = 0;
        			};        				
                	var myObj = {Server:
									{                    	
                					id: serverId,
                					hostUrl: hostUrl,
                					hostServer: hostServer,
                					name: name,
                					isDailyRun: isDailyRun,
                					runSchedule: runSchedule,
                					user: user,
                					password: password
									}	
                	};
                	var jsonStr = Ext.encode(myObj);

                	Ext.Ajax.request({
                		url: 'http://' + ipPort + '/bpcsaveserver/' + serverId,
                		method: 'PUT',
                		jsonData: jsonStr,
                		success: function(response){
                			var obj = Ext.decode(response.responseText);
                			var serverId = obj.server.id;
                			
                			if (win.action != 'edit') 
                				me_server_server.profileTab.onServersModified();
                			
                			Ext.Ajax.request({
								url: 'http://' + ipPort + '/bpcmetadata',
								method: 'GET',
								success: function(response){
									var metaData = Ext.decode(response.responseText);
									var profilegroups = new Array;
									if (metaData.profilegroups != null) {
										if (!(metaData.profilegroups.length)){
											profilegroups[0] = metaData.profilegroups;
										} else {
											profilegroups = metaData.profilegroups;
										};
									}
									if (win.action != 'edit'){
										if (!profilegroups.length) {
											me_server.store.load();
											caseList.serverStore.load();
											me_server.setLoading(false);
											me_profile.listGrid.store.load();
										} 
										for (i = 0; i < profilegroups.length; i ++){
											var myObj = {
													Profile:{
														id: '',
														groupId: profilegroups[i].id,
														name: '',
														appset: '',
														application: '',
														username: '',
														password: '',
														serverId: serverId	        						
													}
											};
											var jsonStr = Ext.encode(myObj);
											Ext.Ajax.request({
												url: 'http://' + ipPort + '/bpcsaveprofile/0',
												method: 'PUT',
												jsonData: jsonStr,
												success: function(response){
													me_server.store.load();
													caseList.serverStore.load();
													me_server.setLoading(false);
													me_profile.listGrid.store.load();
												},
												callback: function(){
												}
											});
										};
									} else {
										me_server.store.load();
										caseList.serverStore.load();
										me_server.setLoading(false);
									};
//									if (metaData.profilegroups.length){
//										for (i = 0; i < metaData.profilegroups.length; i ++){
//											var myObj = {
//					        						Profile:{
//					        							id: '',
//					        							groupId: metaData.profilegroups[i].id,
//					        							name: '',
//					        							appset: '',
//					        							application: '',
//					        							username: '',
//					        							password: '',
//						        						serverId: serverId	        						
//					        						}
//					        				};
//					        				var jsonStr = Ext.encode(myObj);
//					        				Ext.Ajax.request({
//					        					url: 'http://' + ipPort + '/BpcTesterWeb/bpcsaveprofile/0',
//					        					method: 'PUT',
//					        					jsonData: jsonStr,
//					        					success: function(response){
//					        						me_server.store.load();
//					        					},
//					        					callback: function(){
//					        					}
//					        				});
//										}
//									} else {
//										var myObj = {
//				        						Profile:{
//				        							id: '',
//				        							groupId: metaData.profilegroups.id,
//				        							name: '',
//				        							appset: '',
//				        							application: '',
//				        							username: '',
//				        							password: '',
//					        						serverId: serverId		        						
//				        						}
//				        				};
//				        				var jsonStr = Ext.encode(myObj);
//				        				Ext.Ajax.request({
//				        					url: 'http://' + ipPort + '/BpcTesterWeb/bpcsaveprofile/0',
//				        					method: 'PUT',
//				        					jsonData: jsonStr,
//				        					success: function(response){
//				        						me_server.store.load();
//				        					},
//				        					callback: function(){
//				        					}
//				        				});
//									};
									
								}
							});
                		},
                		callback: function(){
//                			me_server.store.load();
//                			me_server.doLayout();
                			win.close();
                		}
                	});
        		}
        	},{xtype:'hiddenfield', width: 5},{
        		xtype: 'button',
        		text: 'Cancel',
        		handler: function(){
        			win.close();
        		}
        	}]
        }]
    }, {
    	region: 'center',
//    	width: '50%',
    	border: 0,
        height: '100%',
        items: [{
        	xtype: 'container',
        	layout: 'hbox',
        	items: [{
//        		flex: 1,
        		xtype: 'fieldcontainer',
            	padding: 3,
                fieldLabel: 'Daily run',
                labelAlign: 'top',
                defaultType: 'checkboxfield',
                items: [
                    {
                        name      : 'isDailyRun',
                        inputValue: '0',
                        id        : 'isDailyRun',
                        handler: function(checkbox, checked){
                        	if (checked){
//                        		var field = win.getComponent('runSchedule');
                        		var field = win.items.items[1].items.items[0].items.items[1];
                        		field.setDisabled(false);
                        	} else {
                        		var field = win.items.items[1].items.items[0].items.items[1];
                        		field.setDisabled(true);
                        	}
                        }                                               	
                    }
                ]
        	},{
//        		flex:2,
        		fieldLabel: 'Time',
            	padding: 3,
            	width: 194,
        		labelAlign: 'top',
        		disabled: true,
        		xtype: 'timefield',
        		id: 'runSchedule'
        	}]
        },{
        	xtype: 'textfield',
        	padding: 3,
        	width: 250,
        	fieldLabel: 'Username',
        	labelAlign: 'top',
        	id: 'user'
        },{
        	xtype: 'textfield',
        	padding: 3,
        	width: 250,
        	inputType: 'password',
        	fieldLabel: 'Password',
        	labelAlign: 'top',
        	id: 'password'
        }]
    }]
})